<?php

  // Parameter validation
  if ( !isset($_GET['latA']) || !isset($_GET['longA']) || !isset($_GET['latB']) || !isset($_GET['longB']) )
  {
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-type: text/html');
    die("latA,longA,latB,longB parameters needed.");
  }

  $longA = stripslashes($_GET['longA']);
  $latA = stripslashes($_GET['latA']);
  $longB = stripslashes($_GET['longB']);
  $latB = stripslashes($_GET['latB']);

  if (!is_numeric($longA) || !is_numeric($latA) || !is_numeric($longB) || !is_numeric($latB))
  {
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-type: text/html');
    die("latA,longA,latB,longB parameters must be numeric values.");
  }

  // Connect to PostgreSQL
  $db = pg_connect("host=localhost dbname=nutsgeo user=postgres password=postgresql");

  if (!$db)
  {
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-type: text/html');
    die('Failed to connect to PostgreSQL. Error: ' . pg_last_error());
  }

  // Perform the SQL query
  $wktBBox = "POLYGON((".$longA." ".$latA.",".$longB." ".$latA.",".$longB." ".$latB.",".$longA." ".$latB.",".$longA." ".$latA."))";

  // Perform the SQL query
  $sql = "SELECT r.uri FROM regions r WHERE ST_ContainsProperly(ST_GeomFromText('".$wktBBox."', 4326),r.shape)";

  $result = pg_query($db, $sql);

  pg_close($dbconn); 

  // Set MIME Type to 'application/rdf+xml'
  header('Content-type: application/rdf+xml; charset=utf-8');

  // Echo XML header as a string, so it is not treated as an opening PHP tag.
  echo '<?xml version="1.0" encoding="utf-8"?>';
?>

<rdf:RDF 
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" 
  xmlns:spatial="http://geovocab.org/spatial#"
  xmlns:ngeo="http://geovocab.org/geometry#"
  xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">

  <rdf:Description rdf:about="">
    <rdfs:comment>Source: NUTS Linked Data Services (http://nuts.geovocab.org/).</rdfs:comment>
  </rdf:Description>

  <rdf:Description rdf:ID="bbox">
    <ngeo:asWKT><?php echo $wktBBox; ?></ngeo:asWKT>
  <?php while ( $row = pg_fetch_array($result) ): ?>
    <spatial:PPi rdf:resource="<?php echo $row[0]; ?>"/>
  <?php endwhile; ?>
  </rdf:Description>
  
</rdf:RDF>
